package com.yungu.swift.api.utils;

import com.yungu.swift.api.config.NacosListener;
import com.yungu.swift.assets.driver.model.dto.DriverFaceRecognitionDto;
import com.yungu.swift.base.ResponseData;
import com.yungu.swift.utils.DateUtils;
import com.yungu.swift.utils.StringUtils;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.multipart.MultipartFile;

import java.io.*;
import java.net.MalformedURLException;
import java.net.URL;
import java.util.Date;

@Slf4j
public class FileUploadUtil {

    private static final String IMAGES_PATH = "static/images";
    private static final String FILES_PATH = "files";

    /**
     * 文件上传目录
     *
     * @param file
     * @param appid
     * @param mobile
     * @return返回访问地址
     */
    public static ResponseData<String> uploadFile(MultipartFile file, String appid, String mobile) {
        String fileName = buildFileName(file.getOriginalFilename());
        //文件上传路径
        String path = File.separator + appid + File.separator + mobile + File.separator + FILES_PATH + File.separator + fileName;
        try {
            File f = createFile(NacosListener.SYS_CONFIG.getUploadPath() + path);
            if (f == null) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "创建文件'" + file.getName() + "'失败");
            }
            file.transferTo(f);
            return ResponseData.buildSuccessResponse("文件上传成功", path);
        } catch (IOException e) {
            log.error("uploadFile file transferTo error. filePath:{}", path, e);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "文件上传失败");
    }

    /**
     * 上传图片保存方法
     *
     * @param file
     * @param appid
     * @param mobile
     * @param imageType
     * @return
     */
    public static ResponseData<String> uploadImage(MultipartFile file, String appid, String mobile, String imageType) {
        String fileName = buildFileName(file.getOriginalFilename());
        String filePath = File.separator + appid + File.separator + mobile + File.separator + imageType + File.separator + fileName;
        try {
            File imageFile = createFile(NacosListener.SYS_CONFIG.getUploadPath() + filePath);
            if (imageFile == null) {
                return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "创建图片文件失败");
            }
            log.info("fileName :{}开始上传", fileName);
            file.transferTo(imageFile);
            return ResponseData.buildSuccessResponse("图片上传成功", filePath);
        } catch (IOException e) {
            log.error("file transferTo error. filePath:{}", filePath, e);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "图片上传失败");
    }

    /**
     * H5司机申请上传图片保存方法
     *
     * @param fileByteData
     * @param originalFilename
     * @param appid
     * @param mobile
     * @param imageType
     * @return
     */
    public static ResponseData<String> uploadImage(byte[] fileByteData, String originalFilename, String appid, String mobile, String imageType) {
        String fileName = buildFileName(originalFilename);
        String path = File.separator + appid + File.separator + mobile + File.separator + imageType + File.separator + fileName;
        File imageFile = createFile(NacosListener.SYS_CONFIG.getUploadPath() + path);
        if (imageFile == null) {
            return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "创建图片文件失败");
        }
        try (// 创建文件输出流
             FileOutputStream outputStream = new FileOutputStream(imageFile)) {
            // 文件输出流写到服务器端
            outputStream.write(fileByteData);
            return ResponseData.buildSuccessResponse("图片上传成功", path);
        } catch (IOException e) {
            log.error("uploadImage outputStream write error,fileName:{}", fileName, e);
        }
        return ResponseData.buildErrorResponse(ResponseData.ERROR_CODE, "图片上传失败");
    }


    private static String buildFileName(String originalFilename) {
        return DateUtils.format(new Date(), "yyyyMMddHHmmss") + "-" + StringUtils.buildUUID() + "-" + originalFilename;
    }

    private static File createFile(String filePath) {
        String directoryPath = filePath.substring(0, filePath.lastIndexOf(File.separator));
        File directory = new File(directoryPath);
        boolean status = true;
        if (!directory.exists()) {
            status = directory.mkdirs();
        }
        File file = new File(filePath);
        if (!file.exists()) {
            try {
                status = file.createNewFile();
            } catch (IOException e) {
                log.error("createNewFile error . filePath:{}", filePath, e);
            }
        }
        if (status) {
            return file;
        }
        return null;
    }

    /**
     * 人脸识别通过URL获取图片再上传到图片服务器
     *
     * @param appid
     * @param driverFaceRecognitionDto
     * @return
     */
    public static DriverFaceRecognitionDto uploadImageByUrl(String appid, DriverFaceRecognitionDto driverFaceRecognitionDto) {
        URL url;
        try {
            url = new URL(driverFaceRecognitionDto.getFacePic());
            DataInputStream dataInputStream = new DataInputStream(url.openStream());
            String[] fileUrl = driverFaceRecognitionDto.getFacePic().split("\\.");
            String fileName = System.currentTimeMillis() + "." + fileUrl[fileUrl.length - 1].split("\\?")[0];
            String fileUploadPath = File.separator + appid + File.separator + driverFaceRecognitionDto.getMobile() +
                    File.separator + "faceRecognition" + File.separator;
            String path = NacosListener.SYS_CONFIG.getUploadPath() + fileUploadPath + fileName;
            File directory = new File(NacosListener.SYS_CONFIG.getUploadPath() + fileUploadPath);
            if (!directory.exists()) {
                directory.mkdirs();
            }
            File file = new File(path);
            if (!file.exists()) {
                file.createNewFile();
            }
            FileOutputStream fileOutputStream = new FileOutputStream(file);
            ByteArrayOutputStream output = new ByteArrayOutputStream();

            byte[] buffer = new byte[1024];
            int length;
            while ((length = dataInputStream.read(buffer)) > 0) {
                output.write(buffer, 0, length);
            }
            fileOutputStream.write(output.toByteArray());
            dataInputStream.close();
            fileOutputStream.close();
            //重新赋值图片路径
            driverFaceRecognitionDto.setFacePic(fileUploadPath + fileName);
        } catch (MalformedURLException e) {
            driverFaceRecognitionDto.setFacePic(null);
            log.error("FileUtils uploadImageByUrl MalformedURLException", e);
        } catch (IOException e) {
            driverFaceRecognitionDto.setFacePic(null);
            log.error("FileUtils uploadImageByUrl IOException", e);
        }
        return driverFaceRecognitionDto;
    }

}
